920G - List Of Integers - CodeForces Solution


binary search bitmasks brute force combinatorics math number theory *2200

Please click on ads to support us..

C++ Code:

#include <vector>
#include <cstring>
#include <iostream>

const int maxn = 1.8e7;
bool pr[maxn + 100];
std::vector<long long> pint, f;

void fac(int x) {
  f.clear();
  for (auto i : pint) {
    if (x % i != 0)
      continue;
    if (i * i > x)
      break;
    f.push_back(i);
    while (x % i == 0)
      x /= i;
  }
  if (x != 1)
    f.push_back(x);
}

int solve(int val) {
  int ret = 0;
  int lim = 1 << f.size();
  for (int j = 1; j < lim; j++) {
    int tp = 1, ct = 0;
    for (int i = 0; i < (int)f.size(); i++) {
      if ((j >> i) & 1) {
        tp *= f[i];
        ct++;
      }
    }
    ret += (ct % 2 ? 1 : -1) * val / tp;
  }
  return val - ret;
}

int main() {
  std::memset(pr, true, sizeof(pr));
  pr[0] = pr[1] = false;
  for (int i = 2; i * i <= maxn; i++)
    if (pr[i])
      for (int j = i * i; j <= maxn; j += i)
        pr[j] = false;
  for (int i = 2; i <= maxn; i++)
    if (pr[i])
      pint.push_back(i);
  int cas, x, p, k;
  std::cin >> cas;
  while (cas--) {
    std::cin >> x >> p >> k;
    fac(p);
    int a1 = solve(x), L = x + 1, R = maxn, ans = 0;
    while (L <= R) {
      int mid = L + (R - L) / 2;
      int val = solve(mid) - a1;
      if (val >= k)
        R = mid - 1, ans = mid;
      else
        L = mid + 1;
    }
    std::cout << ans << "\n";
  }
  return 0;
}
// GURNfUXbeFUgWADpjlcjThLMPrjzNxYlxnsXimJDsEcsnXlOdFiUvDGOYjALGsPKLFGSsdmhVGgNCFyjeGJoXlzMcZzpEhCtWcQVpvajxWGEkejTwSLZbwDXWXsAqTYM


Comments

Submit
0 Comments
More Questions

1358D - The Best Vacation
1620B - Triangles on a Rectangle
999C - Alphabetic Removals
1634C - OKEA
1368C - Even Picture
1505F - Math
1473A - Replacing Elements
959A - Mahmoud and Ehab and the even-odd game
78B - Easter Eggs
1455B - Jumps
1225C - p-binary
1525D - Armchairs
1257A - Two Rival Students
1415A - Prison Break
1271A - Suits
259B - Little Elephant and Magic Square
1389A - LCM Problem
778A - String Game
1382A - Common Subsequence
1512D - Corrupted Array
667B - Coat of Anticubism
284B - Cows and Poker Game
1666D - Deletive Editing
1433D - Districts Connection
2B - The least round way
1324A - Yet Another Tetris Problem
246B - Increase and Decrease
22E - Scheme
1566A - Median Maximization
1278A - Shuffle Hashing